package com.tyun.modules.sys.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.tyun.common.scheduler.SchedulerUtils;
import com.tyun.modules.sys.entity.TimerJob;
import com.tyun.modules.sys.mapper.TimerJobMapper;
import com.tyun.modules.sys.service.ITimerJobService;
import org.quartz.CronTrigger;
import org.quartz.Scheduler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.List;

/**
 * 定时任务管理
 *
 * @author congcong tao
 * @date 2018/9/20 17:32
 */
@Service("timerJobService")
public class TimerJobServiceImpl extends ServiceImpl<TimerJobMapper, TimerJob> implements ITimerJobService {

    @Autowired
    private Scheduler scheduler;

    @PostConstruct
    public void initScheduleJob() {
        TimerJob recordJob = new TimerJob();
        recordJob.setJobStatus("2");
        List<TimerJob> jobs = this.selectList(new EntityWrapper<>(recordJob));
        if (jobs == null || jobs.size() == 0) {
            return;
        }
        for (TimerJob record : jobs) {
            String name = record.getJobName();
            String group = record.getJobGroup();
            CronTrigger cronTrigger = SchedulerUtils.getCronTrigger(scheduler, name, group);
            if (cronTrigger == null) {
                SchedulerUtils.createScheduleJob(record, scheduler);
            } else {
                SchedulerUtils.updateScheduleJob(scheduler, record);
            }
        }
    }
}
